package com.shelpe.services.sinbadgateway.entity.jpa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.apache.commons.lang.StringUtils;

import lombok.Getter;
import lombok.Setter;

@Entity(name = "products")
@Setter
@Getter
public class Product {
	@Id
	@Column(name = "num_iid")
	private long productID;
	@Column(name = "title")
	private String productName;
	@Column(name = "user_id")
	private long userID;
	@Column(name = "pic_url")
	private String pictureUrl;
	@Column(name = "item_imgs")
	@Convert(converter = ItemImgsConverter.class)
	private List<String> itemImgs;
	@Column(name = "cid")
	private long categoryID;
	@Column(name = "cat_name")
	private String categoryName;

	private int salesCount;
	private Date publishTime;

	public static class ItemImgsConverter implements AttributeConverter<List<String>, String> {
		@Override
		public String convertToDatabaseColumn(List<String> attribute) {
			return attribute != null ? ("[" + StringUtils.join(attribute, ",") + "]") : "";
		}

		@Override
		public List<String> convertToEntityAttribute(String dbData) {
			if (!(dbData.equals(""))) {
				String str = dbData.replaceAll("(?:\\[|\\]|\")", "");
				String[] st = str.split(",");
				List<String> ss = java.util.Arrays.asList(st);
				ss = new ArrayList<String>();
				for (String s : st) {
					ss.add("http:" + s.replaceAll("\\\\/", "/"));
				}
				return ss;
			}
			return null;
		}

	}
}
